package com.yxkj.railservicer.util;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.util.Log;

import com.yxkj.railservicer.application.MyApplication;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import static android.content.Context.ALARM_SERVICE;

/**
 * Created by xuyu on 2017/3/13.
 */

public class HeartBreakUtil {

    /**
     * 启动定时任务
     * @param intentName
     */
    public void startRepeatTask(String intentName) {
        //创建Intent对象，actionYW_HEART_BREAK_EVENT
        Intent intent = new Intent(intentName);

        //定义一个PendingIntent对象，PendingIntent.getBroadcast包含了sendBroadcast的动作。
        //也就是发送了action 为"YW_HEART_BREAK_EVENT"的intent
//        PendingIntent pi = PendingIntent.getBroadcast(this,0,intent,0);
        PendingIntent pi = PendingIntent.getBroadcast(MyApplication.getContext(),0,intent,PendingIntent.FLAG_UPDATE_CURRENT);

        //AlarmManager对象,注意这里并不是new一个对象，Alarmmanager为系统级服务
        AlarmManager am = (AlarmManager)MyApplication.getContext().getSystemService(ALARM_SERVICE);

        //设置闹钟从当前时间开始，每隔5s执行一次PendingIntent对象pi，注意第一个参数与第二个参数的关系
        // 5分钟后通过PendingIntent pi对象发送广播
//        am.setRepeating(AlarmManager.RTC,System.currentTimeMillis(),10*1000,pi);
        am.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),5*60*1000,pi);
    }

    /**
     * 停止定时任务
     * @param intentName
     */
    public void stopRepeatTask(String intentName){
        Intent intent = new Intent(intentName);
//        PendingIntent pi = PendingIntent.getBroadcast(this,0,intent,0);
        PendingIntent pi = PendingIntent.getBroadcast(MyApplication.getContext(),0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
        //PendingIntent.FLAG_CANCEL_CURRENT
        AlarmManager am = (AlarmManager)MyApplication.getContext().getSystemService(ALARM_SERVICE);
        am.cancel(pi);
    }

    /**
     * 设置工作状态
     * @param client
     * @param context
     * @param status
     */
    public static void setWorkStack(OkHttpClient client, Context context,Integer status){
        if( client == null ){
            client = new OkHttpClient();
        }

        if(context==null){
            context = MyApplication.getContext();
        }

        String token = SPUtil.getString( context, "token" );
        String channelId = SPUtil.getString(context,"channelId");

        if(token == null || "".equals(token)){
            return;
        }
        if(channelId == null || "".equals(channelId)){
            return;
        }

        String login = "?channelId=" + channelId + "&deviceType=android&status="+((status != null)?status:"");
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.set_work_status_url + login)
                .build();
        Log.e("sendHeartBBreakRequest=",login);

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
//                Log.d("xy", "发送设备状态失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
//                String jsonData = response.body().string();
//                Log.d("xy", "发送设备状态成功" + jsonData);
            }
        });

        token = null;
        channelId = null;
        login = null;
    }

    public static void  sendHeartBreakPacket( OkHttpClient client, Context context,Integer status){
        Log.e("EE","sendHeartBreakPacket. begin");
        if( client == null ){
            client = new OkHttpClient();
        }

        if(context==null){
            context = MyApplication.getContext();
        }

        String token = SPUtil.getString( context, "token" );
        String channelId = SPUtil.getString(context,"channelId");

        if(token == null || "".equals(token)){
            Log.e("EE","token为空");
            return;
        }
        if(channelId == null || "".equals(channelId)){
            Log.e("EE","channelId为空");
            return;
        }

        String login = "?channelId=" + channelId + "&deviceType=android&status="+((status != null)?status:"");
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.heart_break_url + login)
                .build();
        Log.e("sendHeartBBreakRequest=",ContentUtil.heart_break_url+login);

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("xy", "发送设备状态失败");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                Log.e("xy", "发送设备状态成功" + jsonData);
            }
        });

        token = null;
        channelId = null;
        login = null;
        Log.e("EE","sendHeartBreakPacket. end");
    }
}
